﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;

namespace ConsoleApp1.Requests
{
    public class IpInfoRequest
    {
		private string Host;
		private string Port;
		private string Access;
		private string Secret;
		private bool IsProxy;
		public string MakeRequests(bool isproxy = true, string host = "http://http-dyn.abuyun.com",string port= "9020", string acc= "HZ783119Z786X1UD",string secret= "BE35B11C1932B6CC")
		{
			HttpWebResponse response;
			string responseText=string.Empty;
			IsProxy = isproxy;
			Secret = secret;
			Access = acc;
			Port = port;
			Host = host;
			if (Request_ipinfo_io(out response))
			{
				responseText = ReadResponse(response);

				response.Close();
			}
			return responseText;
		}

		private static string ReadResponse(HttpWebResponse response)
		{
			using (Stream responseStream = response.GetResponseStream())
			{
				Stream streamToRead = responseStream;
				if (response.ContentEncoding!=null&&response.ContentEncoding.ToLower().Contains("gzip"))
				{
					streamToRead = new GZipStream(streamToRead, CompressionMode.Decompress);
				}
				else if (response.ContentEncoding != null && response.ContentEncoding.ToLower().Contains("deflate"))
				{
					streamToRead = new DeflateStream(streamToRead, CompressionMode.Decompress);
				}

				using (StreamReader streamReader = new StreamReader(streamToRead, Encoding.UTF8))
				{
					return streamReader.ReadToEnd();
				}
			}
		}

		private bool Request_ipinfo_io(out HttpWebResponse response)
		{
			response = null;

			try
			{
				HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://ipinfo.io/");

				request.UserAgent = "Mozilla/5.0 (Windows NT; Windows NT 10.0; zh-CN) WindowsPowerShell/5.1.19041.1";
                if (IsProxy)
				{
					//request.Headers.Set(HttpRequestHeader.ProxyAuthorization, "Basic SEkyM0w4UjkxMUcwQzI2RDo0N0FCOTAzQzcxRTE0RkIw");

					// 设置代理服务器
					var proxy = new WebProxy();
					proxy.Address = new Uri(string.Format("{0}:{1}",Host,Port ));
					proxy.Credentials = new NetworkCredential(Access, Secret);

					ServicePointManager.Expect100Continue = false;

					request.Proxy = proxy;
				}

				response = (HttpWebResponse)request.GetResponse();
			}
			catch (WebException e)
			{
				if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
				else return false;
			}
			catch (Exception)
			{
				if (response != null) response.Close();
				return false;
			}

			return true;
		}
	}
}
